<template>
  <view class="share-page">
    <image style="width: 100rpx; height: 100rpx" :src="src"></image>
    <button @click="handleSave">保存图片</button>
  </view>
</template>
<script>
export default {
  name: "",
  data() {
    return {
      bjImg: "/static/hb.png",
      src: "https://pic1.zhimg.com/80/v2-58fe538a59f870407b1435bfd45893ed_720w.jpeg",
    };
  },
  onLoad() {},
  methods: {
    // 检查权限
    checkPermission() {
      return new Promise((resolve, reject) => {
        uni.getSetting({
          success: (res) => {
            if (!res.authSetting["scope.writePhotosAlbum"]) {
              // 如果没有权限，获取权限
              uni.authorize({
                scope: "scope.writePhotosAlbum",
                success: () => {
                  resolve();
                },
                fail: (err) => {
                  console.log("授权失败", err);
                  // 用户拒绝授权，引导用户去设置页面

                  
                  uni.showModal({
                    title: "提示",
                    content: "需要您授权保存相册权限，是否去设置？",
                    success: (res) => {
                      if (res.confirm) {
                        uni.openSetting({
                          success: (settingRes) => {
                            console.log("== 打开设置成功 ", settingRes);

                            if (
                              settingRes.authSetting["scope.writePhotosAlbum"]
                            ) {
                              resolve();
                              console.log("== 1111 成功 ");
                            } else {
                              console.log("== 22222 失败 ");
                              reject(new Error("用户未授权"));
                            }
                          },
                          fail(err) {
                            console.log("== 打开设置失败 ", err);
                          },
                        });
                      } else {
                        reject(new Error("用户取消授权"));
                      }
                    },
                  });
                },
              });
            } else {
              // 已有权限
              resolve();
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    // 下载网络图片
    downloadImage(url) {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url: url,
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res.tempFilePath);
            } else {
              reject(new Error("下载失败"));
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    // 保存图片到相册
    saveImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.saveImageToPhotosAlbum({
          filePath: filePath,
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    // 处理保存操作
    async handleSave() {
      try {
        // uni.showLoading({
        //   title: "保存中...",
        // });

        wx.getSetting({
          success(res) {
            console.log(" ==  当前设置", res.authSetting);
            // 根据返回的权限状态进行相应的逻辑处理
          },
        });

        return
        // 1. 检查权限
        await this.checkPermission();

        // 2. 下载图片（如果是网络图片）
        let imagePath = this.src;
        if (this.src.startsWith("http")) {
          imagePath = await this.downloadImage(this.src);
        }

        // 3. 保存图片
        await this.saveImage(imagePath);

        uni.hideLoading();
        uni.showToast({
          title: "保存成功",
          icon: "success",
        });
      } catch (err) {
        uni.hideLoading();
        console.error("保存失败:", err);
        uni.showToast({
          title: err.message || "保存失败",
          icon: "none",
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.share-page {
  background: #fff;
  position: relative;
  overflow: hidden;
  min-height: 100vh;
  .msg-box {
    display: flex;
    align-items: center;
    text-align: center;
    justify-content: center;
  }
  .share-page-box {
    margin: 40rpx auto;
    position: relative;
    overflow: hidden;
    box-shadow: 0rpx 6rpx 20rpx 6rpx rgba(0, 0, 0, 0.2);
  }
  .share-page-btn {
    margin: 0 40rpx 50rpx;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
